<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\Goods;
use app\model\LotusLamp;
use app\model\Temple;
use app\model\TempleImage;
use think\facade\Db;

/**
 * @extends Service<LotusLampService>
 */
class LotusLampService extends Service
{
    public function getList($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['tradeNo']) && $searchQuery['tradeNo'] != '') {
            $w[] = ['trade_no', '=', $searchQuery['tradeNo']];
        }
        if (!empty($searchQuery['deviceNo']) && $searchQuery['deviceNo'] != '') {
            $w[] = ['device_no', '=', $searchQuery['deviceNo']];
        }
        if (!empty($searchQuery['templeName']) && $searchQuery['templeName'] != '') {
            $w[] = ['temple_name', '=', $searchQuery['templeName']];
        }
        if (!empty($searchQuery['lampSwitch']) && $searchQuery['lampSwitch'] != '') {
            $w[] = ['lamp_switch', '=', $searchQuery['lampSwitch']];
        }
        if (!empty($searchQuery['lampStatus']) && $searchQuery['lampStatus'] != '') {
            $w[] = ['lamp_status', '=', $searchQuery['lampStatus']];
        }
        if (!empty($searchQuery['llStatus']) && $searchQuery['llStatus'] != '') {
            $w[] = ['status', '=', $searchQuery['llStatus']];
        }
        if (!empty($searchQuery['temple_id']) && $searchQuery['temple_id'] != '') {
            $w[] = ['temple_id', '=', $searchQuery['temple_id']];
        }

        if (!empty($searchQuery['timeValues'])) {
            if (!is_array($searchQuery['timeValues'])) {
                $timeValues = json_decode($searchQuery['timeValues']);
            } else {
                $timeValues = $searchQuery['timeValues'];
            }
            $w[] = ['create_time', 'between', $timeValues];
        }
        $w[] = ['is_delete', '=', 0];
        $map = LotusLamp::where($w)->page($page, $limit);
        $list = $map->select();
        if (!empty($list)) {
            $list = $list->toArray();
            $temple_ids = array_column($list, 'temple_id');
            $templelist = (new Temple())->where('temple_id', 'in', $temple_ids)->select();
            if ($templelist) {
                $templelist = $templelist->toArray();
                $templelist = array_column($templelist, null, 'temple_id');
                foreach ($list as &$item) {
                    $item['account'] = $item['temple_id'] > 0 ? $templelist[$item['temple_id']]['account'] : '';
                    $item['adcode'] = $item['temple_id'] > 0 ? $templelist[$item['temple_id']]['adcode'] : '';
                    $item['alias'] = $item['temple_id'] > 0 ? $templelist[$item['temple_id']]['alias'] : '';
                    $item['rod_num'] = $this->isTwoDigits($item['rod_num']) ? $item['rod_num'] : $this->padWithZero($item['rod_num']);
                    $item['code_str'] = $item['adcode'] . '-' . $item['pno'] . '-' . $item['rod_num'];
                }
            }

        }

        return [
            'total' => $map->count(),
            'list' => $list,
        ];
    }

    public function info($id)
    {
        $info = LotusLamp::where('id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        $templeInfo = (new Temple())->where('temple_id', $info['temple_id'])->find()->toArray();
        $info = $info->toArray();
        $info['account'] = $templeInfo['account'];
        return $info;
    }

    public function del($id)
    {
        $info = LotusLamp::where('id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        return $info->save(['is_delete' => 1]);
    }

    public function bind($data, $id)
    {
        Db::startTrans();
        try {
            $info = LotusLamp::where('id', $id)->find();
            if (empty($info)) {
                throw new \Exception('数据不存在');
            }
            $map = [];
            if (!empty($data['device_no']) && $data['device_no'] != '') {
                $map['device_no'] = $data['device_no'];
            }
            if (!empty($data['lamp_device_no']) && $data['lamp_device_no'] != '') {
                $map['lamp_device_no'] = $data['lamp_device_no'];
            }
            $info->save($map);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return true;
    }

    public function save($data, $id = null)
    {
        Db::startTrans();
        try {
            $lotusLamp = [];
            if (!empty($data['device_no']) && $data['device_no'] != '') {
                $lotusLamp['device_no'] = $data['device_no'];
            }
            if (!empty($data['lamp_device_no']) && $data['lamp_device_no'] != '') {
                $lotusLamp['lamp_device_no'] = $data['lamp_device_no'];
            }
            if (!empty($data['lamp_status']) && $data['lamp_status'] != '') {
                $lotusLamp['lamp_status'] = $data['lamp_status'];
            }
            if (!empty($data['lamp_switch']) && $data['lamp_switch'] != '') {
                $lotusLamp['lamp_switch'] = $data['lamp_switch'];
            }
            if (!empty($data['temple_id']) && $data['temple_id'] != '') {
                $lotusLamp['temple_id'] = $data['temple_id'];
                $temple = Temple::where('temple_id', $data['temple_id'])->find();
                if (empty($temple)) {
                    throw new \Exception('寺庙不存在');
                }
                $temple = $temple->toArray();
                $lotusLamp['temple_name'] = $temple['name'];
            }

            if (empty($id)) {
                LotusLamp::create($lotusLamp);
            } else {
                $info = LotusLamp::where('id', $id)->find();
                if (empty($info)) {
                    throw new \Exception('数据不存在');
                }
                $info->save($lotusLamp);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return true;
    }

    public function updateAll($projectId = '')
    {
        $url = 'http://device.api.fjxmlz.com:18081/api/devices';
        $params = [];
        if ($projectId) {
            $params['projectId'] = $projectId;
        }
        $header = [
            'Content-Type: application/json'
        ];
        $params = $params ? json_encode($params) : '{}';
        $result = $this->request_post($url, $header, $params);
        $result = json_decode($result, true);
        if (!empty($result['data'])) {
            foreach ($result['data'] as $value) {
                $w = [];
                $w[] = ['device_no', '=', $value['sn']];
                $w[] = ['is_delete', '=', 0];
                $info = LotusLamp::where($w)->find();
                if ($info) {
                    continue;
                }
                $data = [
                    'device_no' => $value['sn'],
                    'lamp_device_no' => $value['sn'],
                    'lamp_status' => 1,
                    'lamp_switch' => 1,
                ];
                $this->save($data);
            }
        }
        return true;
    }


    private function request_post($url = '', $header = array(), $data_string = '')
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        } else {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data_string))
            );
        }
        $result = curl_exec($ch);
        return $result;
    }

    public function downloadFile($url)
    {
        $root = __DIR__ . "/../../public";
        $filePath = $root . $url;
        $filename = time() . '.png';
        // 检测文件是否存在
        if (!file_exists($filePath)) {
            return false;
        }
        // 打开文件
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . $filename);
        readfile($filePath);
        return true;
    }

    public function isTwoDigits($number)
    {
        return strlen((string)$number) >= 2;
    }

    public function padWithZero($number)
    {
        return str_pad($number, 2, '0', STR_PAD_LEFT);
    }


}